package com.example.aop;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yanzhao
 * @date 2022/6/2 16:32
 * @since 1.0.0
 */
public class DefaultAdvisorChainFactory implements AdvisorChainFactory {

    public List<Object> getInterceptors(AdvisedSupport config, Method method, Class<?> targetClass) {

        List<Object> interceptorList = new ArrayList<>();
        AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
        List<Advisor> advisors = config.getAdvisors();

        for (int i = 0; i < advisors.size(); i++) {
            Advisor advisor = advisors.get(i);
            if (advisor instanceof PointcutAdvisor) {
                PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;

                MethodMatcher methodMatcher = pointcutAdvisor.getPointcut().getMethodMatcher();
                if (methodMatcher.matches(method)) {
                    MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
                    interceptorList.addAll(Arrays.asList(interceptors));
                }
            }
        }
        return interceptorList;
    }
}
